// 卡片管理
// 导入数据库
const db = require("../db/index");

// 发表出售卡片
/**
 * body
 * @param {message,img_url,price,room_id} req
 * @param {*} res
 */
exports.addBuyGoods = (req, res) => {
  const getbuysinfo = {
    // 内容 时间 发的用户名
    ...req.body,
    moment: new Date(),
    // 作者id
    user_id: req.user.id,
  };
  const sql = `insert into buy set ?`;

  db.query(sql, getbuysinfo, (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc("发布物品失败！");
    res.cc("发布物品成功", 0);
  });
};

// 获取闲置卡
/**
 *
 * @param {} req
 * @param {message , img_url,price,room_id,username} res
 */
exports.getBuys = (req, res) => {
  const sql = `select buy.* ,users.username  from buy,users where buy.is_delete !=1 and buy.user_id = users.id  order by  buy.moment desc  `;

  db.query(sql, (err, results) => {
    if (err) return res.cc(err);
    res.send({
      message: "获取留言成功",
      data: results,
      status: 0,
    });
  });
};

// 获取我的闲置卡
exports.getMyBuys = (req, res) => {
  const sql = `select * from buy where user_id = ? and is_delete != 1`;

  db.query(sql, [req.user.id], (err, results) => {
    if (err) return err;
    if (results.length == 0) return res.cc("没有查到对应数据！");
    res.send({
      status: 0,
      message: "获取成功！",
      data: results,
    });
  });
};

// 删除个人闲置卡片
/**
 *params
 * @param buy_id req
 * @param {*} res
 */
exports.deleteMyBuys = (req, res) => {
  const sql = `update buy set is_delete = ? where user_id = ? and id = ? `;
  db.query(sql, [1, req.user.id, req.query.buy_id], (err, results) => {
    if (err) return err;
    if (results.affectedRows !== 1) return res.cc("删除失败！稍后再试");
    res.send({
      status: 0,
      message: "删除成功！",
    });
  });
};

//
/**认领
 *  body code  0为还原 1为更新
 * @param {losthelp_id ,code} req
 * @param {*} res
 */
exports.updateBuys = (req, res) => {
  const sql = `update  buy set is_find = ? where id = ?`;

  db.query(sql, [req.body.code, req.body.losthelp_id], (err, results) => {
    if (err) return err;
    res.cc("更新成功", 0);
  });
};
